package com.syni.mdd.yhd.common.all.utils.security;

import com.alibaba.fastjson.JSON;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.sjb.common.component.utils.common.utils.RequestHeaderData;
import com.syni.mdd.yhd.common.all.utils.StringUtils;
import com.syni.mdd.sjb.common.component.utils.redis.utils.RedisTemplateUtils;;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @className InterfaceSecurityUtil
 * @description TOO
 * @Author cfx
 * @DATE 2020/4/7 19:50
 * @VERSION 1.0
 **/
public class InterfaceSecurityUtil {
    private static Logger logger = LoggerFactory.getLogger(InterfaceSecurityUtil.class);
    private static String apiKey = "apiMiDongDong0630@";

    public static boolean checkInterfaceSec(String params){
        RequestHeaderData requestHeader = new RequestHeaderData();
        Map<String, Object> paramsMap = JSON.parseObject(params);
        if(paramsMap == null){
            logger.info("请求无效原因：丢失参数...........");
            return false;
        }
        if(!(paramsMap.containsKey("t")
                && paramsMap.containsKey("rs")
                && paramsMap.containsKey("sign"))){
            logger.info("请求无效原因：丢失参数...........");
            return false;
        }
        String t = paramsMap.get("t").toString();
        String randomStr = paramsMap.get("rs").toString();
        String sign = paramsMap.get("sign").toString();
        if (!(StringUtils.isNotBlank(t) && StringUtils.isNotBlank(randomStr)
                && StringUtils.isNotBlank(sign))) {
            logger.info("请求无效原因：丢失参数...........");
            return false;
        }
        Integer timestamp = Integer.parseInt(t, 16);
        System.out.println("请求时间戳：" + timestamp);
        int nowTime = (int) (System.currentTimeMillis() / 1000);
        if (nowTime - timestamp > 300) {
            logger.info("请求无效原因：5分钟之前的请求");
            return false;
        }
        String URI = requestHeader.getHttpServletRequest().getRequestURI();
        String serverSign = com.syni.mdd.yhd.common.all.utils.WebUtils.MD5(apiKey + URI + t + randomStr).toLowerCase();
        if (!serverSign.equals(sign)) {
            //兼容转发过来的路径
            URI = "/MDD_API" + URI;
            serverSign = com.syni.mdd.yhd.common.all.utils.WebUtils.MD5(apiKey + URI + t + randomStr).toLowerCase();
            if (!serverSign.equals(sign)) {
                logger.info("请求无效原因：sign匹配失败");
                return false;
            }
        }
        if (!RedisTemplateUtils.getRedisTemplate().opsForValue().setIfAbsent(Constants.REDIS_KEY_API_INTECEPTOR + sign, 1, 5, TimeUnit.MINUTES)) {
            logger.info("请求无效原因：sign已被使用");
            return false;
        }
        return true;
    }
}
